package com.sec.etech.employeesync.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.config.ConfigManager;
import com.sec.etech.employeesync.entity.OrgEmployeeEducationalExperience;
import com.sec.etech.employeesync.mapper.OrgEmployeeEducationalExperienceMapper;
import com.sec.etech.employeesync.service.EducationalExperienceService;
import com.sec.etech.sys.util.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openbpm.org.api.model.IUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : 齐马的作品
 * @version : 1.0
 * @date : 2025/5/7 22:33
 * @description:
 */
@Component
@Slf4j
public class EducationalExperienceHandler {

    @Resource
    OrgEmployeeEducationalExperienceMapper eduExpMapper;
    @Autowired
    private EducationalExperienceService educationalExperienceService;
    @Autowired
    private ConfigManager configManager;

    private final Map<Long, List<OrgEmployeeEducationalExperience>> employeeEducationalExperienceMap = new HashMap<>();

    public void preCreateConfig(JSONArray etPa9009Array, IUser iUser) {
        etPa9009Array.parallelStream()
                .map(obj -> (JSONObject) obj)
                .forEach(experienceData -> {
                    ContextUtil.setCurrentUser(iUser);
                    // 毕业院校
                    String zhrjybyyx = experienceData.getString("ZHRJYBYYX");
                    if (StringUtils.isNotBlank(zhrjybyyx)) {
                        configManager.createConfig("school", zhrjybyyx);
                    }

                    // 专业
                    String zhrjyzyf = experienceData.getString("ZHRJYZYF");
                    if (StringUtils.isNotBlank(zhrjyzyf)) {
                        configManager.createConfig("major", zhrjyzyf);
                    }
                });
    }

    public void insertEducationalExperience(List<OrgEmployeeEducationalExperience> list, IUser iUser) {
        ContextUtil.setCurrentUser(iUser);
        educationalExperienceService.saveBatch(list);
    }

    public OrgEmployeeEducationalExperience convertToMainWorkExperience(Long employeeId, JSONObject experienceData) {
        OrgEmployeeEducationalExperience experience = new OrgEmployeeEducationalExperience();
        experience.setEmployeeid(employeeId);
        experience.setStartDate(parseDate(experienceData.getString("ZHRJYBD")));
        experience.setEndDate(parseDate(experienceData.getString("ZHRJYED")));
        experience.setActive(1);

        // 毕业院校
        String zhrjybyyx = experienceData.getString("ZHRJYBYYX");
        if (StringUtils.isNotBlank(zhrjybyyx)) {
            experience.setSchoolId(configManager.getConfigId("school", zhrjybyyx));
        }

        // 专业
        String zhrjyzyf = experienceData.getString("ZHRJYZYF");
        if (StringUtils.isNotBlank(zhrjyzyf)) {
            experience.setMajorId(configManager.getConfigId("major", zhrjyzyf));
        }

        // 学历
        String zhrjyxl = experienceData.getString("ZHRJYXL");
        if (StringUtils.isNotBlank(zhrjyxl)) {
            experience.setEducationId(configManager.getConfigId("education", zhrjyxl));
        }

        // 学位
        String zhrjyxwf = experienceData.getString("ZHRJYXWF");
        if (StringUtils.isNotBlank(zhrjyxwf)) {
            experience.setDegreeId(configManager.getConfigId("degree", zhrjyxwf));
        }

        // 学习形式
        String zhrjyxs = experienceData.getString("ZHRJYXS");
        if (StringUtils.isNotBlank(zhrjyxs)) {
            experience.setLearningFormId(configManager.getConfigId("learningForm", zhrjyxs));
        }

        return experience;
    }

    private Date parseDate(String dateString) {
        if (StringUtils.isBlank(dateString)) {
            return null;
        }
        try {
            return new SimpleDateFormat("yyyyMMdd").parse(dateString);
        } catch (ParseException e) {
            log.error("日期解析错误: {}", dateString, e);
            return null;
        }
    }

    public boolean checkIfExists(Long employeeId, OrgEmployeeEducationalExperience experienceData) {
        List<OrgEmployeeEducationalExperience> employeeExperienceList = employeeEducationalExperienceMap.getOrDefault(employeeId, new ArrayList<>());

        return employeeExperienceList.parallelStream()
                .anyMatch(experience -> isExperienceMatch(experience, experienceData));
    }

    private boolean isExperienceMatch(OrgEmployeeEducationalExperience experience, OrgEmployeeEducationalExperience experienceData) {
        Date startDate = experience.getStartDate();
        Date endDate = experience.getEndDate();
        Long schoolId = experience.getSchoolId();
        Long majorId = experience.getMajorId();
        Long educationId = experience.getEducationId();
        Long degreeId = experience.getDegreeId();
        Long learningFormId = experience.getLearningFormId();

        return dateEqual(startDate, experienceData.getStartDate())
                && dateEqual(endDate, experienceData.getEndDate())
                && longEqual(schoolId, experienceData.getSchoolId())
                && longEqual(majorId, experienceData.getMajorId())
                && longEqual(educationId, experienceData.getEducationId())
                && longEqual(degreeId, experienceData.getDegreeId())
                && longEqual(learningFormId, experienceData.getLearningFormId());
    }

    public static boolean longEqual(Long num1, Long num2) {
        // 如果两个都是null，则相等
        if (num1 == null && num2 == null) {
            return true;
        }
        // 如果一个为null而另一个不为null，则不相等
        if (num1 == null || num2 == null) {
            return false;
        }
        // 两个都不为null，比较数值
        return num1.equals(num2);
    }


    public boolean dateEqual(Date date1, Date date2) {
        // 如果两个都是null，则相等
        if (date1 == null && date2 == null) {
            return true;
        }
        // 如果一个为null而另一个不为null，则不相等
        if (date1 == null || date2 == null) {
            return false;
        }
        // 两个都不为null，比较时间
        return date1.equals(date2);
    }

    public void initAllExperiences() {
        List<OrgEmployeeEducationalExperience> allExperienceList = eduExpMapper.selectList(Wrappers.<OrgEmployeeEducationalExperience>lambdaQuery()
                .eq(OrgEmployeeEducationalExperience::getActive, 1));

        Map<Long, List<OrgEmployeeEducationalExperience>> tempMap = allExperienceList.parallelStream()
                .collect(Collectors.groupingBy(OrgEmployeeEducationalExperience::getEmployeeid, Collectors.toList()));

        employeeEducationalExperienceMap.clear();
        employeeEducationalExperienceMap.putAll(tempMap);
    }
}
